package org.jeecg.modules.controller;

/**
 * @Author: nc
 * @Date: 2023/2/8 12:37
 * @Description:
 */


import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.mapper.dto.ChatGptTalkDTO;
import org.jeecg.modules.service.IChatgptTalkInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * ChartGPT
 * @Author: nc
 * @Date: 2023/2/3 14:25
 * @Description:
 */
@Api(tags="7.ChartGPT")
@RestController
@RequestMapping("/boot/chartGPTController")
@Slf4j
public class ChartGPTController {

    @Autowired
    private IChatgptTalkInfoService chatgptTalkInfoService;

    private static final String API_KEY = "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";
    /**
     * 发送请求
     * @param prompt
     * @return
     */
    @ApiOperation("测试")
    @RequestMapping(value = "/bootTest", method = RequestMethod.GET)
    public Result<?> bootTest(String prompt,String conversationId)  throws Exception  {
        String apiKey = API_KEY;
        String url = "https://api.openai.com/v1/completions";
        String response = generateText(prompt, apiKey, url,conversationId);
        System.out.println(response);
        Gson gson = new Gson();
        Map<String,String> map = new HashMap<>();
        map = gson.fromJson(response, map.getClass());
        return Result.ok(map);
    }

    private static String generateText(String prompt, String apiKey, String url,String conversationId) throws IOException {
        String engine = "text-davinci-003";
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setRequestProperty("Conversation-Id", conversationId);
        connection.setDoOutput(true);
        String requestBody = "{\"model\": \"" + engine + "\",\"prompt\":\"" + prompt + "\",\"max_tokens\":4000,\"temperature\":0}";
        connection.getOutputStream().write(requestBody.getBytes(StandardCharsets.UTF_8));

        Scanner scanner = new Scanner(connection.getInputStream());
        String response = scanner.useDelimiter("\\A").next();
        scanner.close();

        return response;
    }

    @RequestMapping(value = "/chatGPTtalk", method = RequestMethod.POST)
    public Result<String> chatGPTtalk(@RequestBody ChatGptTalkDTO chatGptTalkDTO, HttpServletRequest request)  throws Exception  {
        String sessionId = null;
        String text = null;
        text = chatGptTalkDTO.getInText();
        sessionId = chatGptTalkDTO.getUserId();
        String conversationId = null;
        conversationId =  chatgptTalkInfoService.getConversationId(sessionId);
        String outText = chatgptTalkInfoService.chatGPT(text,conversationId,sessionId);
        return Result.ok(outText);
    }

    @RequestMapping(value = "/talkTTS", method = RequestMethod.POST)
    public Result<String> talkTTS(@RequestBody ChatGptTalkDTO chatGptTalkDTO)  throws Exception  {
        String soundUrl = null;
        String text = null;
        text= chatGptTalkDTO.getInText();
        soundUrl = chatgptTalkInfoService.tts(text);
        log.info(soundUrl);
        return Result.ok(soundUrl);
    }
}
